package cas.ihep.pwa.fcn;

import alluxio.AlluxioURI;
import cas.ihep.alluxio.AlluxioBlock;
import cas.ihep.alluxio.AlluxioFile;
import cas.ihep.alluxio.AlluxioSystem;
import cas.ihep.pwa.api.IGlobalSet;
import cas.ihep.pwa.api.IRunningParam;
import cas.ihep.pwa.entity.ComputeResult;
import cas.ihep.pwa.entity.ComputeResultMc;
import cas.ihep.pwa.evtgen.EvtPDL;
import cas.ihep.spark.JobParser;
import scala.Tuple2;

import java.io.Serializable;
import java.util.List;

public class BaseFcn implements Serializable{

    private static final long serialVersionUID=0xcafebabe9264340L;
    //    Broadcast<JobParser> parser;
//    Broadcast<EvtPDL> pdl;
//    Broadcast<double[]> vpars;
//    Broadcast<String> bdecay;
    JobParser parser;
    EvtPDL pdl;
    double[] vpars;
    String bdecay;

    static native String thcalamps(String path, double[] vpars, List<Tuple2<Long,ComputeResultMc>> lst, EvtPDL pdl, IGlobalSet gset, IRunningParam rp);
    static native String bgcalamps(String path, double[] vpars, double[] outval, EvtPDL pdl, IGlobalSet gset, IRunningParam rp);
    static native String dtcalamps(String path, double[] vpars, double[] outval, EvtPDL pdl, IGlobalSet gset, IRunningParam rp);
    public static native int link(String oldpath,String newpath);
    static void addTupleMc(List<Tuple2<Long,ComputeResult>> lst,long evtid,double t,double a,double msig[]){
        lst.add(new Tuple2<>(evtid,new ComputeResultMc(t,a,msig)));
    }

    static {
        System.loadLibrary("sparkpwa");
        registerNatives(EvtPDL.class,IGlobalSet.class,IRunningParam.class);
    }

    private static native void registerNatives(Class<EvtPDL> jlass,Class<IGlobalSet> klass,Class<IRunningParam>  llass);

    private static native void mmapdecay(String name);
    private static volatile boolean inited=false;

    BaseFcn(){}

//    BaseFcn(Broadcast<EvtPDL> p, Broadcast<JobParser> pa,Broadcast<double[]> vs,Broadcast<String> decay){
//        pdl=p;
//        parser=pa;
//        vpars=vs;
//        bdecay=decay;
//    }

    BaseFcn(EvtPDL p,JobParser jp,double pars[],String d){
        pdl=p;
        parser=jp;
        vpars=pars;
        bdecay=d;
    }

    static void mmapDecay(String decay)throws Exception{
        if (!inited){
            synchronized (BaseFcn.class){
                if (!inited){
                    AlluxioSystem asys=AlluxioSystem.get();
                    AlluxioFile afile=asys.open(new AlluxioURI(decay));
                    AlluxioBlock ablk=afile.getBlock(0);
                    mmapdecay(ablk.getBlockPath());
                    ablk.close();
                    afile.close();
                    inited=true;
                }
            }
        }
    }
}
